package com.macro.cloud.service;

import com.macro.cloud.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * Created by macro on 2019/9/30.
 */
@Service
public class UserService implements UserDetailsService {

    private List<User> userList;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostConstruct
    public void initData() {
        String password = passwordEncoder.encode("123456");
        userList = new ArrayList<>();
        userList.add(new User("0f40a55f-19a1-4a43-a51e-92444842fd74","zhangsan", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
        userList.add(new User("e9e64076-d527-4144-a674-ea52031e949f","13233866775", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
        userList.add(new User("fd5245c7-4d7f-4679-96f5-354977bf5319","79527743@qq.com", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
        userList.add(new User("d8820d8d-e9d6-48d5-973d-b7b197d2eede","zhaoliu", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
        userList.add(new User("706dc1fc-21ef-46a8-8dbb-44daf30b4858","admin", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<User> findUserList = userList.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(findUserList)) {
            return findUserList.get(0);
        } else {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
    }

    public User getUserByUsername(String username) throws UsernameNotFoundException {
        List<User> findUserList = userList.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(findUserList)) {
            return findUserList.get(0);
        } else {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
    }
}
